from flask import Flask, render_template, request, flash
from flask_migrate import Migrate
import config
from bluePrint.auth import bp as auth_bp
from bluePrint.queMan import bp as queMan_bp
from bluePrint.GPT import bp as GPT_bp
from flask_login import LoginManager, login_required, current_user
from exts import db
from exts import mail
from models import UserModel
from models import TopicModel

app = Flask(__name__)

# 配置文件
app.config.from_object(config)

# 绑定邮件
mail.init_app(app)

# 注册蓝图
app.register_blueprint(auth_bp)
app.register_blueprint(queMan_bp)
app.register_blueprint(GPT_bp)

# 绑定数据库
db.init_app(app)
# 迁移数据库
migrate = Migrate(app, db)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = '/auth/login'  # 设置未登录时重定向到的视图



@login_manager.user_loader
def load_user(user_id):
    return UserModel.query.get(int(user_id))


# 根目录，登录页面
@app.route('/', methods=['GET', 'POST'])
@login_required
def index():
    if request.method == 'GET':
        # 查询当前用户的所有的题目，组成列表
        TopicModels = TopicModel.query.filter(TopicModel.user_id == current_user.id).all()
        return render_template('index.html', TopicModels=TopicModels, user_name=current_user.username, email=current_user.email)


if __name__ == '__main__':
    app.run(debug=True)
